#!/usr/bin/env bash

source ../../lib/shell/common.sh
env
function check() {
	which nvme > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		echo "no nvme command, please install nvme-cli rpm"
		test_fail
	fi
}

function get_nvme_drives_info() {
	echo "get all NVMe drives:"
	nvme list
	echo
}

#For the NVMe device given, sends an identify command and provides the result and returned structure.
function nvme_related_records() {
	local nvme_log_some_steps="id-ctrl \
				   id-ns \
				   gen-hostnqn
				"
	for step in $nvme_log_some_steps; do
		echo "send $step to ${DEVNAME}"
		if [ "${step}" = "list-ns" ]; then
			nvme "${step}" "${DEVNAME}" -a
		else
			nvme "${step}" "${DEVNAME}" -H
		fi
		[ $? -ne 0 ] && echo "failed to run ${step}" && test_fail
		echo
	done
}

#Get all logs
function nvme_getall_logs() {
	local scsi_host_path="/sys/class/scsi_host"
	local log_types="fw smart error"
        if echo "$DEVICE_NAME" | grep -q QEMU; then
		local log_types="fw smart"
	fi
	#nvme log
	for log_type in ${log_types}
	do
		echo "get NVMe ${log_type} log for device ${DEVNAME}"
		nvme "${log_type}-log" "${DEVNAME}"
		[ $? -ne 0 ] && echo "failed to get NVMe ${log_type} log" && test_fail
		echo
	done

	#sys log
        local regex="host\*"
	for sys_log in ${scsi_host_path}/host*/nvme_info
	do
		if [[ "$(echo "${sys_log}"|grep "$regex")" != "" ]];then
			echo "no system log of nvme"
			break
		else
			cat "${sys_log}"
			[ $? -ne 0 ] && echo "failed to get output from ${sys_log}" && test_fail
			echo
		fi
	done
}

# # # # # # # # # # # # # # main # # # # # # # # # # # #
print_test_info "NVMe"
show_module_info "$MODULE"
get_nvme_drives_info
nvme_related_records
nvme_getall_logs
test_pass
